from datetime import datetime
import json
from database.database import MedicalRecord,db,MedicalRecordMedicine,Medicine
from utils.jsonutil import AlchemyEncoder


# 获取病人当前有效的病历id
def get_valid_record_id(patient_id):
    # 获取当前时间
    now = datetime.now()
    # 获取end_time在当前时间之后的该病人的病历id
    records = MedicalRecord.query.filter(MedicalRecord.patient_id==patient_id,MedicalRecord.end_time>now).all()
    record_list = []
    for record in records:
        record_list.append(record.id)
    return record_list

# 获取病人当前有效的病历
def get_valid_record(patient_id):
    # 获取当前时间
    now = datetime.now()
    # 获取end_time在当前时间之后的该病人的病历id
    records = MedicalRecord.query.filter(MedicalRecord.patient_id==patient_id,MedicalRecord.end_time>now).all()
    record_list = []
    for record in records:
        record_list.append(json.loads(json.dumps(record,cls=AlchemyEncoder,ensure_ascii=False)))
    return record_list

# 根据病人当前有效的病历id获取病人当前有效的药品
def get_valid_medicine(patient_id):
    record_list = get_valid_record_id(patient_id)
    # 获取病历id在record_list中的药品
    medicines = MedicalRecordMedicine.query.filter(MedicalRecordMedicine.medical_record_id.in_(record_list)).all()
    medicine_list = []
    for medicine in medicines:
        medicine_list.append(json.loads(json.dumps(medicine,cls=AlchemyEncoder,ensure_ascii=False)))
    return medicine_list

    